package com.thirtydays.frame.base.http.okhttp

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.thirtydays.frame.base.http.error.ApiException
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter
import java.lang.reflect.Type

/**
 * @创建者：小垚
 * @时间：2021/8/1614:50
 * @描述：自定义解析类
 */
class CustomResponseConverter<T>(gson: Gson, adapter: TypeAdapter<T>, mType: Type) : Converter<ResponseBody, T> {
    private var mGson = gson
    private var mAdapter= adapter
    private var mType = mType

    override fun convert(value: ResponseBody): T? {
        try {
            val body = value.string()
            var json = JSONObject(body)
            val code = json.getInt("error_code")
            val msg = json.getString("error_msg")
            when(code){
                0 ->{
                    return mGson.fromJson(body, mType)
                }
                else ->{
                    throw ApiException(msg)
                }
            }
        } catch (e: Exception) {
            throw e
        } finally {
            value.close()
        }
    }
}